package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @date: 2024/7/27 15:14
 * @author: yz
 * @version: 1.0
 */
@Aspect
@Component
@Slf4j
public class RequiresLoginAspect {


    private final RedisTemplate<Object, Object> redisTemplate;

    public RequiresLoginAspect(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 用户拦截切面定义处理
     * @param joinPoint 切点方法对象
     * @param requiresLogin 自定义登录注解
     * @return 返回目标方法的执行结果
     */
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(requiresLogin)")
    @SneakyThrows
    public Object doConcurrentOperation(ProceedingJoinPoint joinPoint, RequiresLogin requiresLogin) {
        Object proceed;

        // 获取用户登录信息的cache key，包含token
        String loginKey = getLoginKey();
        // 尝试从redis中获取user信息
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(loginKey);

        // 判断是否需求拦截，如果要求登录且用户信息为空，抛出异常业务状态
        if (requiresLogin.required() && userInfoVo == null) {

            // 拦截--响应208
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);

        }

        // 登录--存储userid--thread local
        if (userInfoVo != null) {
            AuthContextHolder.setUserId(userInfoVo.getId());
            AuthContextHolder.setLoginKey(loginKey);
        }

        // 执行目标方法
        proceed = joinPoint.proceed();

        // 清除thread local--防止内存泄漏 --防止信息泄露
        AuthContextHolder.removeUserId();
        AuthContextHolder.removeLoginKey();

        return proceed;
    }

    private static String getLoginKey() {
        // 过请求上下文对象RequestContextHolder获取请求属性对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 判断请求属性对象是否为null
        if (requestAttributes == null) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 将RequestAttributes（接口）转为ServletRequestAttributes（实现类）
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        // 获取请求对象
        HttpServletRequest request = attributes.getRequest();
        // 获取请求头中存储的token
        String token = request.getHeader("token");
        // 指定存储用户登录信息key
        return RedisConstant.USER_LOGIN_KEY_PREFIX + token;
    }


}
